package com.itheima.controller;

import com.itheima.pojo.Emp;
import com.itheima.pojo.Result;
import com.itheima.service.LoginService;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * CTassName: loginController
 * Package: com.itheima.controller
 * Description:
 * 登录功能
 *
 * @Author xw
 * @Create 2023/11/7 10:48
 * @Version 1.0
 */

@Slf4j
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private LoginService loginService;

    // 登录
    @PostMapping
    public Result login(@RequestBody Emp emp) {

        // 日志
        log.info("username：{},password{}", emp.getUsername(), emp.getPassword());

        // 判断是否的的登录成功
        Emp emp1 = loginService.login(emp.getUsername(), emp.getPassword());

        // 发生一个 token 令牌
        if (emp1 != null) {
            // 自定义信息
            HashMap<String, Object> claims = new HashMap<>();
            // 添加信息
            claims.put("id",emp1.getId());
            claims.put("username",emp1.getUsername());
            claims.put("name",emp1.getName());

            // 使用 JWT 工具类，生成身份令牌
            String s = JwtUtils.generateJwt(claims);

            return Result.success(s);


        }


        return Result.error("用户名或密码错误");

    }
}
